#!/bin/bash

# Asurada SSO客户端启动脚本

echo "=========================================="
echo "    Asurada SSO 客户端启动脚本"
echo "=========================================="

# 检查Java版本
echo "检查Java环境..."
if ! command -v java &> /dev/null; then
    echo "❌ 错误: 未找到Java环境，请安装JDK 21"
    exit 1
fi

JAVA_VERSION=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2 | cut -d'.' -f1)
if [ "$JAVA_VERSION" -lt 21 ]; then
    echo "❌ 错误: 需要JDK 21或更高版本，当前版本: $JAVA_VERSION"
    exit 1
fi
echo "✅ Java版本检查通过: $(java -version 2>&1 | head -n 1)"

# 检查Maven
echo "检查Maven环境..."
if ! command -v mvn &> /dev/null; then
    echo "❌ 错误: 未找到Maven，请安装Maven 3.6+"
    exit 1
fi
echo "✅ Maven版本: $(mvn -version | head -n 1)"

# 检查Redis连接
echo "检查Redis连接..."
if command -v redis-cli &> /dev/null; then
    if redis-cli ping > /dev/null 2>&1; then
        echo "✅ Redis连接正常"
    else
        echo "⚠️  警告: Redis连接失败，请确保Redis服务正在运行"
        echo "   默认配置: localhost:6379"
    fi
else
    echo "⚠️  警告: 未找到redis-cli，无法检查Redis连接"
fi

# 检查SSO服务端
echo "检查SSO服务端连接..."
if command -v curl &> /dev/null; then
    if curl -s http://localhost:8080/actuator/health > /dev/null 2>&1; then
        echo "✅ SSO服务端连接正常"
    else
        echo "⚠️  警告: 无法连接到SSO服务端 (http://localhost:8080)"
        echo "   请确保Asurada SSO服务端正在运行"
    fi
else
    echo "⚠️  警告: 未找到curl，无法检查SSO服务端连接"
fi

echo ""
echo "开始编译项目..."
mvn clean compile -q

if [ $? -ne 0 ]; then
    echo "❌ 编译失败，请检查代码"
    exit 1
fi
echo "✅ 编译成功"

echo ""
echo "启动应用..."
echo "应用将在以下地址运行:"
echo "  - 首页: http://localhost:8081"
echo "  - 登录页面: http://localhost:8081/login"
echo "  - 受保护页面: http://localhost:8081/protected"
echo "  - 个人信息: http://localhost:8081/profile"
echo ""
echo "按 Ctrl+C 停止应用"
echo "=========================================="

# 启动Spring Boot应用
mvn spring-boot:run